package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.model.admin.dtos.UserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.gateway.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {

    @Override
    public ResponseResult login(UserDto dto) {
        //检查参数
        if (StringUtils.isEmpty(dto.getName()) || StringUtils.isEmpty(dto.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "用户名或密码不能为空");
        }

        //对获取到的数据进行比对
        //1根据用户名在数据库中进行查询
//        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
////        queryWrapper.eq(AdUser::getName, dto.getName());
////        AdUser article = getOne(queryWrapper);
        //根据用户名查询用户
        QueryWrapper<AdUser> queryWrapper = new QueryWrapper<AdUser>();
        queryWrapper.eq("name", dto.getName());
        AdUser user = getOne(queryWrapper);

        //判断查询到的数据为不为空
        if (user == null) {
            //返回用户不存在错误信息
            System.out.println(user);
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
        }
        //对传来的密码进行md5(不可逆)加密
        String pwd = DigestUtils.md5DigestAsHex((dto.getPassword() + user.getSalt()).getBytes());
        //对上传的密码和数据库查到的密码进行比较


        if (!pwd.equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //生成token
        String token = AppJwtUtil.getToken(user.getId().longValue());

        //为了数据安全，需将敏感数据去掉
        user.setPassword("");
        user.setSalt("");

        //封装数据
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("user", user);

        //返回数据
        return ResponseResult.okResult(map);
    }
}
